package com.crm.util;

import java.security.MessageDigest;
import java.sql.Date;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import com.crm.po.Users;

public class RequestEx {

	private static SimpleDateFormat formatCommon = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static String getCheckBox(String[] values, String split){
		if(values == null || values.length == 0){
			return "";
		}
		StringBuffer buffer = new StringBuffer("");
		for(String value : values){
			if(buffer.length() > 0){
				buffer.append(split);
			}
			buffer.append(value);
		}
		return buffer.toString();
	}
	
	public static String getString(String value){
		return value != null && value.trim().length() > 0 ? value: "";
	}
	
	public static String getStringTrim(String value){
		return getString(value).trim();
	}
	
	public static String getStringTrim(String value, String defaultValue){
		String temp = getString(value).trim();
		return temp.length() > 0 ? temp : defaultValue;
	}
	
	public static Double getDouble(String value){
		return value != null && value.trim().length() > 0 ? Double.parseDouble(value.trim()): 0.00;
	}
	
	public static Integer getInteger(String value){
		if(value != null && value.indexOf(".") >= 0){
			value = value.split("\\.")[0];
		}
		try{
			return value != null && value.trim().length() > 0 ? Integer.parseInt(value.trim()): 0;
		}catch(Exception e){
			return 0;
		}
	}
	
	public static Date getSqlDate(String value){
		return value != null && value.trim().length() > 0 ? Date.valueOf(value.trim()): null;
	}
	
	public static java.util.Date getUtilDate(String value){
		java.util.Date tempDate = null;
		try {
			tempDate = value != null && value.trim().length() > 0 ? formatCommon.parse(value.trim()): null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return tempDate;
	}
	
	public static Users getCurUser(HttpServletRequest request){
		Object obj = request.getSession(true).getAttribute(SESSION.USER_SESSION_KEY);
		Users users = null;
		if(obj != null){
			users = (Users) obj;
		}
		return users;
	}
	
	public static String encodeByMD5(String value){
		if(value == null){
			return "";
		}
		char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       
        try {
            byte[] btInput = value.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return "";
        }
	}
	
	public static void main(String[] args) {		
		System.out.println(getInteger("AA.4"));
	}

}
